#include "sysmonitor/resources_monitor.hpp"
#include "sysmonitor/utils.hpp"

#include <iostream>
#include <iomanip>
#include <csignal>
#include <memory>
#include <thread> 

// 全局变量，用于信号处理
std::unique_ptr<sysmonitor::ResourcesMonitor> monitor_ptr;

void signalHandler(int signum) {
    std::cout << "\nInterrupt signal (" << signum << ") received.\n";
    if (monitor_ptr) {
        monitor_ptr->stopMonitoring();
    }
}

void printSystemResources(const sysmonitor::SystemResources& res) {
    // 使用ANSI转义序列清屏并移动光标到左上角
    std::cout << "\033[2J\033[1;1H";
    
    std::cout << "============== System Resource Monitor ==============\n";
    
    // CPU信息
    const auto& cpuInfo = monitor_ptr->getCpuInfo();
    std::cout << "\n--- CPU Info: " << cpuInfo.modelName << " (" << cpuInfo.cores << " Cores, " << cpuInfo.threads << " Threads) ---\n";
    std::cout << "Total Usage: " << std::fixed << std::setprecision(1) << res.cpuUsage.totalUsage << "%\n";
    for (size_t i = 0; i < res.cpuUsage.coreUsages.size(); ++i) {
        std::cout << "Core" << i << ": " << std::setw(5) << res.cpuUsage.coreUsages[i] << "% ";
        if ((i + 1) % 4 == 0 || i == res.cpuUsage.coreUsages.size() - 1) std::cout << "\n";
    }

    // 内存信息
    std::cout << "\n--- Memory & Swap ---\n";
    std::cout << res.memoryInfo.memory.toString() << "\n";
    std::cout << res.memoryInfo.swap.toString() << "\n";
  
    // 磁盘信息
    std::cout << "\n--- Disk Partitions ---\n";
    for (const auto& part : res.diskPartitions) {
        std::cout << part.toString() << "\n";
    }
  
    // 网络流量
    std::cout << "\n--- Network Traffic ---\n";
    for (const auto& traffic : res.networkTraffic) {
        std::cout << std::left << std::setw(10) << traffic.interface << ": "
                  << "RX: " << std::setw(12) << sysmonitor::utils::UnitConverter::formatBytes(static_cast<uint64_t>(traffic.receiveRate)) + "/s"
                  << "TX: " << std::setw(12) << sysmonitor::utils::UnitConverter::formatBytes(static_cast<uint64_t>(traffic.sendRate)) + "/s\n";
    }
    std::cout << "\n=====================================================\n"
              << "Press Ctrl+C to exit." << std::endl;
}

int main() {
    // 注册信号处理函数
    signal(SIGINT, signalHandler);

    // 创建监控配置
    sysmonitor::MonitorConfig config;
    config.updateInterval = std::chrono::seconds(2);

    // 使用智能指针管理监控器对象
    monitor_ptr = std::make_unique<sysmonitor::ResourcesMonitor>(config, printSystemResources);
  
    // 启动监控
    std::cout << "Starting system monitoring...\n";
    // 稍微等待一下，让第一次数据收集完成
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
    monitor_ptr->startMonitoring();
  
    // 等待监控线程结束（当信号处理器调用stopMonitoring后，线程会退出）
    // 主线程可以进入睡眠或等待，直到监控结束
    while (monitor_ptr && monitor_ptr->isRunning()) {
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
  
    std::cout << "\nMonitoring stopped gracefully.\n";
    return 0;
}
